package com.ncmmall.mall.controller.business.marketing;

import cn.hutool.core.convert.Convert;
import com.ncmmall.application.business.marketing.ShoppingCardApplication;
import com.ncmmall.application.business.marketing.ShoppingCardRecordApplication;
import com.feijin.commons.lang.Requires;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCard;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardAddress;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardChannel;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardGoods;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardMerchant;
import com.ncmmall.domain.business.marketing.shoppingcard.QShoppingCardRecord;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCard;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardAddress;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardChannel;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardGoods;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardMerchant;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecord;
import com.ncmmall.domain.business.marketing.shoppingcard.ShoppingCardRecordConsume;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物卡
 *
 * @author likaikai
 * @date 2020-1-14 16:03:35
 */
@Controller
@RequestMapping("/mall/marketing/shoppingCard")
@Slf4j
public class ShoppingCardController {

    @Autowired
    private ShoppingCardApplication shoppingCardApplication;

    @Autowired
    private ShoppingCardRecordApplication shoppingCardRecordApplication;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 购物卡列表
     *
     * @param params     查询参数
     * @param pageParams 分页参数
     * @param export     是否导出
     * @return 购物卡列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, ShoppingCard params, PageParams pageParams, HttpServletResponse response,
                       @RequestParam(defaultValue = "false") boolean export) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());
        Map<String, Object> map = Maps.newHashMap();

        String hql = buildHQL("select s from ShoppingCard s where 1 = 1", map, params);
        QueryPage<ShoppingCard> page = queryChannelService.findPage(hql, pageRequest.setParams(map), ShoppingCard.class);

        if (export) {
            export(response, page.getResult());
            return null;
        }

        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "mall/marketing/shoppingCard/list";
    }


    /**
     * 赠送购物卡
     */
    @RequestMapping(value = "/present/{id}", method = RequestMethod.GET)
    public String present(Model model, @PathVariable long id) {

        List<WebUser> users = queryChannelService.findAll("select u from WebUser u where u.accountNonLocked = true", new HashMap<>(), WebUser.class);
        model.addAttribute("users", users);

        return "mall/marketing/shoppingCard/present";
    }

    /**
     * 赠送购物卡
     */
    @RequestMapping(value = "/present/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> present(@PathVariable long id, Long userId) {

        try {
            Requires.notNull(userId, "请选择用户");
            WebUser user = queryChannelService.findOne(WebUser.class, userId);

            ShoppingCard shoppingCard = queryChannelService.findOne(ShoppingCard.class, id);
            Requires.isTrue(shoppingCard.getNumber() > 0, "购物卡数量不足, 无法赠送");
            shoppingCardApplication.present(shoppingCard, user, Securitys.currentUser());

            return ImmutableMap.of("status", true, "message", "赠送成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("赠送购物卡异常", e);
            return ImmutableMap.of("status", false, "message", "赠送异常");
        }
    }

    /**
     * 导出
     *
     * @param response      响应
     * @param shoppingCards 购物卡
     */
    private void export(HttpServletResponse response, List<ShoppingCard> shoppingCards) {

    }

    private String buildHQL(String hql, Map<String, Object> map, ShoppingCard params) {

        if (StringUtils.isNotBlank(params.getCardNo())) {
            hql += " and s.cardNo like :cardNo";
            map.put("cardNo", params.getCardNo() + "%");
        }

        if (StringUtils.isNotBlank(params.getName())) {
            hql += " and s.name like :name";
            map.put("name", params.getName() + "%");
        }

        if (params.getStatus() > 0) {
            hql += " and s.status = :status";
            map.put("status", params.getStatus());
        }

        if (StringUtils.isNotBlank(params.getStartTime())) {
            Timestamp start = Timestamp.valueOf(params.getStartTime());
            hql += " and s.validStartTime >= :start";
            map.put("start", start);
        }

        if (StringUtils.isNotBlank(params.getStartTime())) {
            Timestamp end = Timestamp.valueOf(params.getEndTime());
            hql += " and s.validEndTime <= :end";
            map.put("end", end);
        }

        hql += " order by s.createTime desc ";

        return hql;
    }


    /**
     * 添加购物卡
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        List<GoodsChannel> goodsChannels = queryChannelService.findAll(QGoodsChannel.goodsChannel.level.eq(1).and(QGoodsChannel.goodsChannel.status.eq(1)), GoodsChannel.class);
        model.addAttribute("goodsChannels", goodsChannels);
        model.addAttribute("_method", "POST");
        model.addAttribute("shoppingCard", new ShoppingCard());

        return "mall/marketing/shoppingCard/form";
    }

    /**
     * 添加购物卡
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(HttpServletRequest request, ShoppingCard shoppingCard) {

        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be Ajax!");
            }

            shoppingCardApplication.create(shoppingCard);

            return ImmutableMap.of("status", true, "message", "创建成功");
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[添加购物卡异常]", e);
            return ImmutableMap.of("status", false, "message", "添加异常");
        }
    }


    /**
     * 购物卡详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    public String detail(@PathVariable long id, Model model) {

        ShoppingCard shoppingCard = queryChannelService.findOne(QShoppingCard.shoppingCard.id.eq(id), ShoppingCard.class);
        shoppingCard.setChannels(queryChannelService.findAll(QShoppingCardChannel.shoppingCardChannel.shoppingCard.id.eq(id), ShoppingCardChannel.class));
        shoppingCard.setGoods(queryChannelService.findAll(QShoppingCardGoods.shoppingCardGoods.shoppingCard.id.eq(id), ShoppingCardGoods.class));
        shoppingCard.setMerchants(queryChannelService.findAll(QShoppingCardMerchant.shoppingCardMerchant.shoppingCard.id.eq(id), ShoppingCardMerchant.class));

        if (shoppingCard.getAreaType() == 2) {
            shoppingCard.setAddresses(queryChannelService.findAll(QShoppingCardAddress.shoppingCardAddress.shoppingCard.id.eq(id), ShoppingCardAddress.class));
        }

        model.addAttribute("card", shoppingCard);

        return "mall/marketing/shoppingCard/detail";
    }


    /**
     * 购物卡发放记录
     */
    @RequestMapping(value = "/{id}/record", method = RequestMethod.GET)
    public String grantList(@PathVariable long id, Model model, ShoppingCardRecord record, PageParams pageParams) {

        String hql = "select r from ShoppingCardRecord r where r.shoppingCard.id = :id";
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);

        hql = buildRecordHql(hql, record, params);
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize()).setParams(params);
        QueryPage<ShoppingCardRecord> page = queryChannelService.findPage(hql, pageRequest, ShoppingCardRecord.class);

        model.addAttribute("page", page);
        model.addAttribute("params", record);

        return "mall/marketing/shoppingCard/record";
    }


    /**
     * 购物卡赠送人
     */
    @RequestMapping(value = "/recipient", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> recipient(long id, HttpServletRequest request) {

        try {

            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            ShoppingCardRecord record = queryChannelService.findOne(QShoppingCardRecord.shoppingCardRecord.id.eq(id), ShoppingCardRecord.class);
            Requires.notNull(record, "记录不存在");

            return ImmutableMap.of(
                    "status", true,
                    "message", "成功",
                    "username", record.getRecipient().getUsername(),
                    "recipientTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getRecipientTime()));

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false);
        } catch (Exception e) {
            log.error("[获取购物卡赠送人异常]", e);
            return ImmutableMap.of("status", false);
        }

    }


    /**
     * 购物卡消费记录
     */
    @RequestMapping(value = "/{id}/consume", method = RequestMethod.GET)
    public String consumeList(@PathVariable long id, ShoppingCardRecordConsume consume, PageParams pageParams, Model model) {

        String hql = "select r from ShoppingCardRecordConsume r where r.shoppingCardRecord.id = :id";
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", id);

        hql = buildConsumeHql(hql, consume, params);
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize()).setParams(params);
        QueryPage<ShoppingCardRecordConsume> page = queryChannelService.findPage(hql, pageRequest, ShoppingCardRecordConsume.class);

        model.addAttribute("page", page);
        model.addAttribute("params", consume);

        return "mall/marketing/shoppingCard/consume";
    }

    /**
     * 购物卡消费记录hql
     */
    private String buildConsumeHql(String hql, ShoppingCardRecordConsume consume, Map<String, Object> params) {
        if (consume.getOrder() != null && StringUtils.isNotBlank(consume.getOrder().getOrderNo())) {
            hql += " and r.order.orderNo like :orderNo";
            params.put("orderNo", consume.getOrder().getOrderNo());
        }
        return hql + " order by r.createTime desc";
    }

    /**
     * 购物卡领取记录hql
     */
    private String buildRecordHql(String hql, ShoppingCardRecord record, Map<String, Object> params) {
        if (record.getUser() != null && StringUtils.isNotBlank(record.getUser().getUsername())) {
            hql += " and r.user.username like :username";
            params.put("username", "%" + record.getUser().getUsername() + "%");
        }
        if (record.getStatus() > 0) {
            hql += " and r.status = :status";
            params.put("status", record.getStatus());
        }
        return hql + " order by r.createTime desc";
    }


    /**
     * 上架
     */
    @RequestMapping(value = "/{id}/enable", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> enable(HttpServletRequest request, @PathVariable long id) {

        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be Ajax!");
            }

            ShoppingCard card = queryChannelService.findOne(QShoppingCard.shoppingCard.id.eq(id), ShoppingCard.class);
            shoppingCardApplication.enable(card);

            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[购物卡上架异常]", e);
            return ImmutableMap.of("status", false, "message", "上架异常");
        }
    }


    /**
     * 下架
     */
    @RequestMapping(value = "/{id}/disable", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> disable(HttpServletRequest request, @PathVariable long id) {

        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be Ajax!");
            }

            ShoppingCard card = queryChannelService.findOne(QShoppingCard.shoppingCard.id.eq(id), ShoppingCard.class);
            shoppingCardApplication.disable(card);

            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[购物卡下架异常]", e);
            return ImmutableMap.of("status", false, "message", "下架异常");
        }
    }

    /**
     * 批量上架
     */
    @RequestMapping(value = "/enables", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> enables(HttpServletRequest request, String ids) {

        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be Ajax!");
            }

            shoppingCardApplication.enables(queryShoppingCardsByIds(ids));
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[购物卡批量上架异常]", e);
            return ImmutableMap.of("status", false, "message", "上架异常");
        }
    }


    /**
     * 批量下架
     */
    @RequestMapping(value = "/disables", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> disables(HttpServletRequest request, String ids) {

        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be Ajax!");
            }

            shoppingCardApplication.disables(queryShoppingCardsByIds(ids));
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[购物卡批量下架异常]", e);
            return ImmutableMap.of("status", false, "message", "下架异常");
        }
    }

    /**
     * 根据购物卡id查找购物卡列表
     *
     * @param ids 多个id以分号拼接的字符串
     * @return 购物卡列表
     */
    private List<ShoppingCard> queryShoppingCardsByIds(String ids) {
        List<Long> idList = Splitter.on(";").splitToList(ids).stream().map(Long::parseLong).collect(Collectors.toList());
        return queryChannelService.findAll(QShoppingCard.shoppingCard.id.in(idList), ShoppingCard.class);
    }


    /**
     * 申请激活列表
     *
     * @param params     查询参数
     * @param pageParams 分页参数
     * @param export     是否导出
     * @return 购物卡列表
     */
    @RequestMapping(value = "/activate/list", method = RequestMethod.GET)
    public String activateList(Model model, ShoppingCardRecord params, PageParams pageParams, HttpServletResponse response,
                               @RequestParam(defaultValue = "false") boolean export) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());
        Map<String, Object> map = Maps.newHashMap();

        String hql = buildActivateHQL("select r from ShoppingCardRecord r where r.activateStatus > 0", map, params);
        QueryPage<ShoppingCardRecord> page = queryChannelService.findPage(hql, pageRequest.setParams(map), ShoppingCardRecord.class);

        if (export) {
            exportActivate(response, page.getResult());
            return null;
        }

        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "mall/marketing/shoppingCard/activate/list";
    }

    /**
     * 激活申请导出
     *
     * @param response 输出
     * @param result   激活申请列表
     */
    private void exportActivate(HttpServletResponse response, List<ShoppingCardRecord> result) {

    }

    /**
     * 申请激活列表hql
     */
    private String buildActivateHQL(String hql, Map<String, Object> map, ShoppingCardRecord params) {

        ShoppingCard card = params.getShoppingCard();
        if (card != null) {
            if (StringUtils.isNotBlank(card.getCardNo())) {
                hql += " and r.shoppingCard.cardNo like :cardNo";
                map.put("cardNo", "%" + card.getCardNo() + "%");
            }
            if (StringUtils.isNotBlank(card.getName())) {
                hql += " and r.shoppingCard.name like :name";
                map.put("name", "%" + card.getName() + "%");
            }
        }

        if (params.getActivateStatus() > 0) {
            hql += " and r.activateStatus = :activateStatus";
            map.put("activateStatus", params.getActivateStatus());
        }

        if (StringUtils.isNotBlank(params.getActivateTimeStr())) {
            List<String> times = Splitter.on(" - ").omitEmptyStrings().trimResults().splitToList(params.getActivateTimeStr());
            hql += " and r.activateApplyTime >= :startTime and r.activateApplyTime <= :endTime";
            map.put("startTime", Timestamp.valueOf(times.get(0) + " 00:00:00"));
            map.put("endTime", Timestamp.valueOf(times.get(1) + " 23:59:59"));
        }

        return hql + " order by r.activateApplyTime desc";
    }


    /**
     * 申请激活详情
     *
     * @param id 用户购物卡id
     */
    @RequestMapping(value = "/activate/{id}/detail", method = RequestMethod.GET)
    public String activateDetail(@PathVariable long id, Model model) {

        ShoppingCardRecord record = queryChannelService.findOne(QShoppingCardRecord.shoppingCardRecord.id.eq(id), ShoppingCardRecord.class);
        model.addAttribute("record", record);

        return "mall/marketing/shoppingCard/activate/detail";
    }


    /**
     * 申请激活审核
     */
    @RequestMapping(value = "/activate", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> activate(ShoppingCardRecord params, HttpServletRequest request) {

        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be ajax!");
            }

            ShoppingCardRecord record = queryChannelService.findOne(QShoppingCardRecord.shoppingCardRecord.id.eq(params.getId()), ShoppingCardRecord.class);
            if (params.getActivateStatus() == 2) {
                List<String> times = Splitter.on(" - ").omitEmptyStrings().trimResults().splitToList(params.getActivateTimeStr());
                shoppingCardRecordApplication.activateSuccess(record, params.getActivateNote(), Timestamp.valueOf(times.get(0) + " 00:00:00"), Timestamp.valueOf(times.get(1) + " 23:59:59"));
            } else {
                shoppingCardRecordApplication.activateFail(record, params.getActivateNote());
            }

            return ImmutableMap.of("status", true);

        } catch (Exception e) {
            log.error("[激活审核异常]", e);
            return ImmutableMap.of("status", false);
        }

    }

    /**
     * 选择商家页
     */
    @RequestMapping(value = "/selectMerchants", method = RequestMethod.GET)
    public String selectMerchants(Model model, PageParams pageParams, @RequestParam String ids) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());

        String hql = "select u from WebUser u where u.role.name = 'MERCHANT' and u.merchantCheckStatus = 2 and u.accountNonLocked = true";

        Map<String, Object> map = Maps.newHashMap();
        if (StringUtils.isNotBlank(ids)) {
            List<String> strings = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids);
            Set<Long> collect = Arrays.stream(Convert.toLongArray(strings)).collect(Collectors.toSet());
            Set<Long> merchantIds = queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.channel.id.in(collect), MerchantGoodsChannel.class).stream().map(MerchantGoodsChannel::getMerchant).map(WebUser::getId).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(merchantIds)) {
                hql += " and u.id in (:ids)";
                map.put("ids", merchantIds);
            }
        }

        hql += " order by u.createTime desc";
        QueryPage<WebUser> page = queryChannelService.findPage(hql, pageRequest.setParams(map), WebUser.class);

        model.addAttribute("page", page)
        .addAttribute("ids", ids);

        return "mall/goods/subject/merchantslist";
    }

    /**
     * 选择商品页
     */
    @RequestMapping(value = "/selectGoods", method = RequestMethod.GET)
    public String selectGoods(Model model, PageParams pageParams, HttpServletRequest request, Goods params, @RequestParam String ids) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());

        int type = 0;
        if (!Strings.isNullOrEmpty(request.getParameter("platformType")) && "1".equals(request.getParameter("platformType"))) {
            type = 1;
        }

        String hql = "select u from Goods u where u.status = 3 and u.isSupplier = :type  ";
        pageRequest.getParams().put("type", type);

        QueryPage<Goods> page = queryChannelService.findPage(builderSQL(hql, pageRequest.getParams(), params, ids), pageRequest, Goods.class);

        model.addAttribute("page", page)
                .addAttribute("ids", ids)
                .addAttribute("platformType", type)
                .addAttribute("params", params)
                .addAttribute("channels", queryChannelService.findAll("select c from GoodsChannel c where c.deleteStatus = 0 and  c.level = 1 and c.status = 1 ", GoodsChannel.class));
        ;

        return "mall/goods/subject/goodslist";
    }

    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, Goods goods, String ids) {

        if (StringUtils.isNotBlank(ids)){
            List<String> strings = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids);
            Set<Long> collect = Arrays.stream(Convert.toLongArray(strings)).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(collect)){
                sql += " and u.merchant.id in (:ids)";
                params.put("ids", collect);
            }
        }

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }

        if (goods.getMerchant() != null && goods.getMerchant().getId() > 0) {
            sql += " and u.merchant.id = :merchantId ";
            params.put("merchantId", goods.getMerchant().getId());
        }

        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status in (3,6) ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }


        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.defaultPrice " + goods.getOrderByPrice();
        } else if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.store " + goods.getOrderByStore();
        } else if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }
}
